<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;



use app\common\model\CourseCollectionsFabulous;
use app\common\model\CourseJoin;
use app\common\model\ForumBbsCommentFabulous;
use app\common\model\ForumBbsFabulous;
use app\common\model\ForumFollow;
use app\common\model\Member;
use app\common\model\Transfer;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use think\Db;
use Think\Log;

/**
 * 商学院逻辑
 */
class Business extends ApiBase
{


    /**
     * 最近更新课程
     */

    public function  recent_course($data){


        $uid=decoded_user_token($data['user_token'],'member_id');
        $where=['status'=>1];
        $list=$this->modelCourseCollections->field('id,cover_id,name,create_time,course_id')->where($where)->limit(5)->order('id desc')->select();

        foreach ($list as $k=>$v){


                 $list[$k]['course_name']=$v->course['name'];
                $list[$k]['avtar']=$v->course->teacher->image;
                 $list[$k]['username']=$v->course->teacher['name'];
                $list[$k]['is_buy']=$v->course->is_buy($uid);
                 unset($v->course->teacher);
                 unset($v->course);
                 $list[$k]['time']=exchange_time($v->create_time);
                 $list[$k]['position']=$v->position;
        }


        return $list;
    }






    /**
     * 热门课堂
     */

    public function  hot_course(){

        $where['a.is_hot']=1;

        $this->modelCourse->alias('a');


        $list=$this->modelCourse->getList($where,'a.cover_id,a.name,a.describe,a.id,a.money,collections,teacher_id','a.sort desc ,a.id desc',false);



        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->image;
            $list[$k]['username']=$v->teacher['name'];
            $list[$k]['identity']=$v->teacher['identity'];
            $list[$k]['learner_count']=$v->learner_count;
            unset($v->teacher);

        }

        return $list;
    }



    /**
     * 推荐课程
     */

    public function  recommended_courses(){

        $where['a.status']=1;

        $this->modelCourse->alias('a');


        $list=$this->modelCourse->getList($where,'a.cover_id,a.name,a.describe,a.id,a.money,collections,type,teacher_id','a.sort desc ,a.id desc');



        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->image;
            $list[$k]['username']=$v->teacher['name'];
            $list[$k]['identity']=$v->teacher['identity'];
            $list[$k]['learner_count']=$v->learner_count;
            unset($v->teacher);
        }

        return $list;
    }





    /***
     * 课堂详情
     */
    public function  course_info($data){

        $uid=decoded_user_token($data['user_token'],'member_id');
        $info=$this->modelCourse->getInfo(['id'=>$data['id']]);
        if(!$info){
            return ajaxreturn(1,lang('该课程不存在'));
        }
        $info->collect;
        $info['learner_count']=$info->learner_count;
        $info['image']=$info->image;
        $info['renew']=$info->renew;
        $info['is_buy']=$info->is_buy($uid);
        $info['intro']=$info->teacher->intro;
        unset($info->teacher);
        return $info;


    }



    /***
     * 购买课堂
     */
    public function  buy_course($data){

        $uid=decoded_user_token($data['user_token'],'member_id');
        $info=$this->modelCourse->getInfo(['id'=>$data['id']]);
        if(!$info){
            return ajaxreturn(1,lang('该课程不存在'));
        }
        if($info->is_buy($uid)==1){
            return ajaxreturn(1,lang('不允许重复购买'));
        }
        $mymember=Member::get($uid);
        if($mymember['pin_password']!=md5($data['pin_password'].'pin')){
            return ajaxreturn(1,lang('PIN密码不正确'));
        }
        Db::startTrans();
        $account=UserAccount::check(['wallet_id'=>1,'user_id'=>$uid],false);
        if($account['balance']<$info['money']){
            return ajaxreturn(1,lang('余额不足'));
        }
        //扣除余额

        try{
            $account->balance-=$info['money'];
            $account->save();


            //写入订单记录
            Transfer::create([
                'type'=>13,
                'form_wallet_id'=>1,
                'before_available_balance'=>$account['balance']+$info['money'],
                'after_available_balance'=>$account['balance'],
                'number'=>$info['money'],
                'user_id'=>$uid,
                'state'=>1,
                'collection_id'=>$data['id']
            ]);

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$info['money'],
                'wallet_id'=>1,
                'before_blance'=>$account->balance+$info['money'],
                'after_blance'=>$account->balance,
                'is_add'=>2,
                'type'=>11
            ]);
            Db::name("member")->where(["id"=>$uid])->setInc("bets_total_balance",$info['money']);
            //写入购买记录
            CourseJoin::create([
                'user_id'=>$uid,
                'course_id'=>$data['id']
            ]);
            Db::commit();
            return ajaxreturn(0,lang('购买成功'));
        }catch (\Exception $e){
            Db::rollback();
//            return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }

    /***
     * 课程详情
     */
    public function  course_collection_info($data){

        $uid=decoded_user_token($data['user_token'],'member_id');
        $info=$this->modelCourseCollections->getInfo(['id'=>$data['id']]);
        if(!$info){
            return ajaxreturn(1,lang('该课程内容不存在'));
        }

        $info['zan']=$info->zan($uid);
        $info['video_url']=$info->video_url;
        $coment=[];
        foreach ($info->reply as  $k=> $v){
            if($v['is_hide']==0 || $v['user_id']==$uid) {
                $coment[$k]['id'] = $v['id'];
                $coment[$k]['user_id'] = $v['user_id'];
                $coment[$k]['user_name'] = $v->user->username;
                $coment[$k]['content'] = $v['content'];
                $coment[$k]['avtar'] = $v->user->avtar;
                $coment[$k]['time'] = exchange_time($v['create_time']);
                $reply=[];
                foreach ($v->reply as $ke => $va) {

                    if ($va['is_hide'] == 0 || $va['uid'] == $uid || $va['user_id'] == $uid) {
                        $reply[$ke]['id'] = $va['id'];
                        $reply[$ke]['uid'] = $va['uid'];
                        $reply[$ke]['user_name'] = $va->user->username;
                        $reply[$ke]['content'] = $va['content'];
                        unset($va->user);
                    }
                }
                $coment[$k]['comment_reply'] = array_merge($reply);
                unset($v->user);
                unset($v->reply);
            }

        }
        $info['comment']=array_merge($coment);
        unset($info->reply);


        return $info;


    }



    /***
     * 课程留言
     */
    public function  collections_message($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $info=$this->modelCourseCollections->getInfo(['id'=>$data['collect_id']]);
        if(!$info){
            return ajaxreturn(1,lang('课程不存在'));
        }
        if(empty($data['content'])){
            return ajaxreturn(1,lang('内容不能为空'));
        }
        $data['user_id']=$uid;
        Db::startTrans();
        try{
            $this->modelCourseCollectionsComment->setInfo($data);

            Db::commit();
            return ajaxreturn(0,lang('留言成功'));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
        }
    }



    /***
     * 留言回复
     */
    public function  collections_message_reply($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $info=$this->modelCourseCollectionsComment->getInfo(['id'=>$data['comment_id']]);
        if(!$info){
            return ajaxreturn(1,lang('该留言不存在'));
        }
        if(empty($data['content'])){
            return ajaxreturn(1,lang('内容不能为空'));
        }
        if(empty($data['uid'])){
            $comment=$this->modelCourseCollectionsComment->getInfo(['id'=>$data['comment_id']]);
            $data['uid']=$comment['user_id'];
        }
        $data['user_id']=$uid;
        Db::startTrans();
        try{
            $result=$this->modelCourseCollectionsCommentReply->setInfo($data);
            //通知用户
            $this->modelCourseNotice->setInfo([
                'user_id'=>$data['uid'],
                'uid'=>$uid,
                'comment_id'=>$result
            ]);
            Db::commit();
            return ajaxreturn(0,lang('回复成功'));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
        }
    }


    /**
     * 课程内容点赞
     */
    public function collection_praise($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $info=$this->modelCourseCollections->getInfo(['id'=>$data['id']]);
        if(!$info){
            return ajaxreturn(1,lang('课程不存在'));
        }
        $info->star+=1;
        $info->save();
        if(CourseCollectionsFabulous::get(['status'=>1,'user_id'=>$uid,'collect_id'=>$data['id']])){
            return ajaxreturn(1,lang('您已赞过'));
        }
        CourseCollectionsFabulous::create([
            'user_id'=>$uid,
            'collect_id'=>$data['id']
        ]);
        return ajaxreturn(0,lang('成功'));
    }










    /***
     * 课程打赏
     */
    public function  reward_colletctions($data){

        $uid=decoded_user_token($data['user_token'],'member_id');
        $info=$this->modelCourseCollections->getInfo(['id'=>$data['id']]);
        if(!$info){
            return ajaxreturn(1,lang('该课程内容不存在'));
        }
        $mymember=Member::get($uid);
        if($mymember['pin_password']!=md5($data['pin_password'].'pin')){
            return ajaxreturn(1,lang('PIN密码不正确'));
        }
        Db::startTrans();
        $account=UserAccount::check(['wallet_id'=>1,'user_id'=>$uid],false);
        if($account['balance']<$data['money']){
            return ajaxreturn(1,lang('余额不足'));
        }


        //扣除余额

        try{
            $account->balance-=$data['money'];
            $account->save();


            //写入订单记录
            Transfer::create([
                'type'=>14,
                'form_wallet_id'=>1,
                'before_available_balance'=>$account['balance']+$data['money'],
                'after_available_balance'=>$account['balance'],
                'number'=>$data['money'],
                'user_id'=>$uid,
                'state'=>1,
                'collection_id'=>$data['id']
            ]);

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$info['money'],
                'wallet_id'=>1,
                'before_blance'=>$account->balance+$data['money'],
                'after_blance'=>$account->balance,
                'is_add'=>2,
                'type'=>12
            ]);
            Db::name("member")->where(["id"=>$uid])->setInc("bets_total_balance",$info['money']);
            Db::commit();
            return ajaxreturn(0,lang('打赏成功'));
        }catch (\Exception $e){
            Db::rollback();
//            return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }
    }





    /***
     * 用户通知列表
     */
    public function  course_notice($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $where['user_id']=$uid;

        $list=$this->modelCourseNotice->getList($where,'*','id desc');

        $where['is_read']=0;
        $where['status']=1;
        $this->modelCourseNotice->where($where)->update(['is_read'=>1]);
        foreach ($list as $k=>$v){
            $list[$k]['username']=$v->touser->username;
            $list[$k]['avtar']=$v->touser->avtar;
            $list[$k]['content']=$v->reply->content;
            unset($v->touser);
            unset($v->reply);
        }

        return $list;

    }







    /***
     * 在线解答
     */
    public function  online_answer($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $info=$this->modelForumBbs->getInfo(['id'=>$data['bbs_id']]);
        if(!$info){
            return ajaxreturn(1,lang('该帖已被删除'));
        }
        if(empty($data['content'])){
            return ajaxreturn(1,lang('内容不能为空'));
        }
        if(!empty($data['comment_id'])){
           $comment=$this->modelForumBbsComment->getInfo(['id'=>$data['bbs_id']]);
           $data['uid']=$comment['user_id'];
        }
        $data['user_id']=$uid;
        Db::startTrans();
        try{
            $this->modelForumBbsComment->setInfo($data);
            //通知用户
            if(empty($data['comment_id'])){
                $data['uid']=$info['user_id'];
            }
            $this->modelForumNotice->setInfo([
                'user_id'=>$data['uid'],
                'uid'=>$uid,
                'bbs_id'=>$data['bbs_id']
            ]);
            Db::commit();
            return ajaxreturn(0,lang('回复成功'));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
        }
    }


    /***
     * 关注/取消关注
     */
    public function  bbs_follow($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $info=ForumFollow::get(['user_id'=>$uid,'uid'=>$data['uid']]);
        if($data['type']==1){
            if($info && $info['status']==1){
                return ajaxreturn(1,lang('您已关注对方'));
            }
            if($info && $info['status']== -1){
                ForumFollow::update(['status'=>1],[
                    'user_id'=>$uid,
                    'uid'=>$data['uid']
                ]);
            } else{
                ForumFollow::create([
                    'user_id'=>$uid,
                    'uid'=>$data['uid']
                ]);
            }
        }else{
            $uid=decoded_user_token($data['user_token'],'member_id');
            ForumFollow::update(['status'=>-1],[
                'user_id'=>$uid,
                'uid'=>$data['uid']
            ]);
        }


        return ajaxreturn(0,lang('成功'));
    }






    /***
     * 清除用户通知列表
     */
    public function  clear_bbs_notice($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $where['user_id']=$uid;
        $where['status']=1;
        $this->modelForumNotice->where($where)->update(['status'=>-1]);
        return ajaxreturn(0,lang('成功'));

    }

    /**
     * 用户主页
     */
    public function user_homepage($data){
        $user=$this->modelMember->getInfo(['id'=>$data['uid']]);
        if(!$user){
            return ajaxreturn(1,lang('用户不存在'));
        }

        $avtar=$user->avtar;
        $follow_count=$this->modelForumFollow->where(['uid'=>$data['uid']])->count();
        $follow=$this->modelForumFollow->where(['user_id'=>$data['uid']])->count();
        return ['avtar'=>$avtar,'follow_count'=>$follow_count,'follow'=>$follow,'uid'=>$data['uid']];

    }


    /***
     * 我的帖子
     */
    public function  my_bbs($data){
        $user=$this->modelMember->getInfo(['id'=>$data['uid']]);
        if(!$user){
            return ajaxreturn(1,lang('用户不存在'));
        }
        $where['user_id']=$data['uid'];
        $list=$this->modelForumBbs->getList($where,'id,user_id,name,content,cate_id,create_time','create_time desc');
        $time=time();
        foreach ($list as $k=>$v){

                $list[$k]['cate_name']=$v->cate['name'];
                $list[$k]['reply_count']= $v->reply_count;
                $minute=floor(($time-$v['create_time'])/60);
                $hour=floor($minute/60);
                $day=floor($hour/24);
                $month=floor($day/30);
                if(floor(($time-$v['create_time']))<1){
                    $list[$k]['time']=floor(($time-$v['create_time'])).lang('秒前');
                }elseif($minute<60){
                    $list[$k]['time']=$minute.lang('分钟前');

                }elseif($hour<24){
                    $list[$k]['time']=$hour.lang('小时前');

                }elseif($day<30){
                    $list[$k]['time']=$day.lang('天前');
                }else{

                    $list[$k]['time']=$month.lang('月前');
                }
            unset($v->reply);
                unset($v->cate);


        }

        return $list;
    }


    /***
     * 我的回帖
     */
    public function  my_bbs_comment($data){
        $user=$this->modelMember->getInfo(['id'=>$data['uid']]);
        if(!$user){
            return ajaxreturn(1,lang('用户不存在'));
        }
        $where['user_id']=$data['uid'];
        $list=$this->modelForumBbsComment->getList($where,'id,user_id,bbs_id,content,create_time','create_time desc');
        $time=time();
        foreach ($list as $k=>$v){

                $list[$k]['name']=$v->bbs['name'];
                $minute=floor(($time-$v['create_time'])/60);
                $hour=floor($minute/60);
                $day=floor($hour/24);
                $month=floor($day/30);
                if(floor(($time-$v['create_time']))<1){
                    $list[$k]['time']=floor(($time-$v['create_time'])).lang('秒前');
                }elseif($minute<60){
                    $list[$k]['time']=$minute.lang('分钟前');

                }elseif($hour<24){
                    $list[$k]['time']=$hour.lang('小时前');

                }elseif($day<30){
                    $list[$k]['time']=$day.lang('天前');
                }else{

                    $list[$k]['time']=$month.lang('月前');
                }

                unset($v->bbs);
        }

        return $list;
    }


    /***
     * 我的关注者
     */
    public function  my_follow($data){
        $user=$this->modelMember->getInfo(['id'=>$data['uid']]);
        if(!$user){
            return ajaxreturn(1,lang('用户不存在'));
        }
        $where['uid']=$data['uid'];
        $list=$this->modelForumFollow->getList($where,'id,user_id,create_time','create_time desc');

        foreach ($list as $k=>$v){

            $list[$k]['username']=$v->user['username'];
            $list[$k]['avtar']=$v->user->avtar;
            unset($v->user);

        }

        return $list;
    }



    /***
     * 正在关注
     */
    public function  follow_user ($data){
        $user=$this->modelMember->getInfo(['id'=>$data['uid']]);
        if(!$user){
            return ajaxreturn(1,lang('用户不存在'));
        }
        $where['user_id']=$data['uid'];
        $list=$this->modelForumFollow->getList($where,'id,uid,create_time','create_time desc');

        foreach ($list as $k=>$v){

            $list[$k]['username']=$v->touser['username'];
            $list[$k]['avtar']=$v->touser->avtar;
            unset($v->touser);

        }

        return $list;
    }


    /***
     * 他的文章
     */
    public function  article_user ($data){
        $user=$this->modelMember->getInfo(['id'=>$data['uid']]);
        if(!$user){
            return ajaxreturn(1,lang('用户不存在'));
        }
        $where['member_id']=$data['uid'];
        $list=$this->modelArticle->getList($where,'id,cover_id,create_time,name,describe,category_id','create_time desc');

        foreach ($list as $k=>$v){

            $list[$k]['cate_name']=$v->cate['name'];
            $list[$k]['image']=$v->image;
            $list[$k]['addtime']=date('Y-m-d',$v->create_time);
            unset($v->cate);

        }

        return $list;
    }





    /**
     * 问答大学
     */

    public function answer_list($data){
        $where['status']=['eq',1];
        if(!empty($data['cate_id'])){
            $where['cate_id']=$data['cate_id'];
        }
        $list=$this->modelCourseQuestion->getList($where,'*','sort desc, id desc');
        foreach ($list as $k=>$v){
            $list[$k]['is_show']=0;
        }
        return $list;
    }




    /**
     * 问答回复
     */

    public function answer_reply($data){

        if($data['type']==1){
            $this->modelCourseQuestion->where(['id'=>$data['id']])->setInc('has_answer',1);
        }else{
            $this->modelCourseQuestion->where(['id'=>$data['id']])->setInc('no_answer',1);
        }
        return ajaxreturn(0,lang('操作成功'));
    }

































    /**
     * 发布话题
     */
    public function issue_topic($data = [])
    {
        $uid=decoded_user_token($data['user_token'],'member_id');

        if(empty($data['cate_id'])){
            return ajaxreturn(1,lang('请选择话题分类'));
        }
        if(empty($data['title'])){
            return ajaxreturn(1,lang('请输入标题'));
        }
        $data['name']=$data['title'];
        if(empty($data['content'])){
            return ajaxreturn(1,lang('请输入内容'));
        }

        $data['user_id']=$uid;
        $this->modelForumBbs->setInfo($data);
        return ajaxreturn(0,lang('发布成功'));


    }
















}
